package com.zxl.live.screen.screen.ui.widget.surface;

import android.graphics.Camera;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.view.MotionEvent;

import com.zxl.live.screen.screen.ui.widget.ScreenSurfaceView;

public class FrameController implements IPanel, Runnable {
	
	private IPanel mCurrentFream;
	
	private ScreenSurfaceView mScreenSurfaceView;

	private static FrameController sInstance;
	
	private FrameController() {
		onCreate();
	}
	
	public static FrameController getInstance() {
		if (null == sInstance) {
			sInstance = new FrameController();
		}
		return sInstance;
	}
	
	public void setScreenSurfaceView(ScreenSurfaceView mScreenSurfaceView) {
		this.mScreenSurfaceView = mScreenSurfaceView;
	}
	
	public void setCurrentFream(IPanel mCurrentFream) {
		this.mCurrentFream = mCurrentFream;
	}

	@Override
	public void doDraw(Camera camera, Matrix matrix, Canvas canvas, Paint paint) {
		if (null != mCurrentFream) {
			mCurrentFream.doDraw(camera, matrix, canvas, paint);
		}
	}

	@Override
	public void onCreate() {
		if (null != mCurrentFream) {
			mCurrentFream.onCreate();
		}
	}

	@Override
	public void onStart() {
		if (null != mCurrentFream) {
			mCurrentFream.onStart();
		}
	}

	@Override
	public void onResume() {
		if (null != mCurrentFream) {
			mCurrentFream.onResume();
		}
	}

	@Override
	public void onStop() {
		if (null != mCurrentFream) {
			mCurrentFream.onStop();
		}
	}

	@Override
	public void onPause() {
		if (null != mCurrentFream) {
			mCurrentFream.onPause();
		}
	}

	@Override
	public void logic() {
		if (null != mCurrentFream) {
			mCurrentFream.logic();
		}
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (null != mCurrentFream) {
			return mCurrentFream.onTouchEvent(event);
		} else {
			return false;
		}
	}

	@Override
	public void run() {
		while (!Thread.interrupted() && mScreenSurfaceView.isStart()) {
			long start = System.currentTimeMillis();
			if (!mScreenSurfaceView.isPause()) {
				logic();
			}
			long sub = System.currentTimeMillis() - start;
			if (sub < ScreenSurfaceView.REFFRESH_TIME) {
				try {
					Thread.sleep(ScreenSurfaceView.REFFRESH_TIME - sub);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
